package com.leetCode.ListNodeDemo;

import com.leetCode.ArrayDemo.NextPermutationDemo;

import java.util.List;

public class MergeTwoListsDemo {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1,new ListNode(2,new ListNode(4)));
        ListNode l2 = new ListNode(1,new ListNode(3,new ListNode(4)));
        ListNode listNode = mergeTwoLists1(l1, l2);
        System.out.println(listNode);
    }

    /**
     * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
     *
     *
     *
     * 示例 1：
     *
     *
     * 输入：l1 = [1,2,4], l2 = [1,3,4]
     * 输出：[1,1,2,3,4,4]
     * 示例 2：
     *
     * 输入：l1 = [], l2 = []
     * 输出：[]
     * 示例 3：
     *
     * 输入：l1 = [], l2 = [0]
     * 输出：[0]
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(0);
        ListNode cur = root;
        while (l1 != null && l2 != null){
           if (l1.val < l2.val){
               cur.next = l1;
               cur = cur.next;
               l1 = l1.next;
           } else {
               cur.next = l2;
               cur = cur.next;
               l2 = l2.next;
           }
        }
        if (l1 == null){
            cur.next = l2;
        } else {
            cur.next = l1;
        }
        return root.next;
    }

    /**
     *
     */
    public static ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode root = new ListNode(0);
        ListNode cur = root;
        while (l1 != null || l2 != null){
            if (l1 != null && l2 == null){
                cur.next = l1;
                l1 = null;
            } else if (l1 == null && l2 != null){
                cur.next = l2;
                l2 = null;
            } else {
                if (l1.val < l2.val){
                    cur.next = l1;
                    cur = cur.next;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    cur = cur.next;
                    l2 = l2.next;
                }
            }
        }
        return root.next;
    }

}
